
package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.domain.*;
import cnhy.salary.service.WageSvc;
import com.easy.query.api4j.sql.SQLWherePredicate;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.easy.query.core.expression.lambda.SQLExpression1;
import com.easy.query.core.proxy.sql.Select;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
import java.io.Serializable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
//import cnhy.salary.service.DailyWageService;
import ling.common.*;
import ling.common.domain.*;

 /** 日工资 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
@Api(tags = "日工资 功能接口")
@RestController
@RequestMapping("/salary/DailyWage")
public class DailyWageController extends EQueryController<DailyWage>{


    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.dailyWage.query)")
    @GetMapping(value = "/{id}")
    public Result<DailyWage> getInfo(@PathVariable("id") Long id)
    {
       return super.getInfo(id);
    }

    @Override
    protected ResultRows<DailyWage> queryPage(Serializable whereObj, PageDomain pageRequest) {
        gainPageDomain(pageRequest);
        var pitem = queryHelper.query().queryable(DailyWage.class)
                .whereObject(whereObj != null, whereObj);
        if (pageRequest instanceof ObjectSort)
            pitem.orderByObject((ObjectSort) pageRequest);
        var pData = pitem
                .orderByAsc(p->p.column(DailyWage::getPostStatus))
                .orderByAsc(p->p.column(DailyWage::getOrderNum))
                .orderByDesc(p -> p.column(DailyWage::getPostType))
                .orderByDesc(p -> p.column(DailyWage::getRatio))
                .orderByAsc(p -> p.column(DailyWage::getId))
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        return toResultRows(pData);
    }

    @ApiOperation("分页列表")
    @PreAuthorize("@ps.any(@pay.dailyWage.list)")
    @GetMapping("list")
    public ResultRows<DailyWage> list(DailyWage dto, PageDomain pageRequest) {
//        queryHelper.entityQuery(DailyWage.class).leftJoin(Employee.class,(p,p1)->p.userId().eq(p1.userId()))
        if (Objects.equals(dto.getDeptId(), -100L))
            dto.setDeptId(getDeptId());
        if(dto.getTime()!=null&&dto.getTime2()==null)
        {
            dto.setTime2(DateUtil.endOfDay(dto.getTime()));
            dto.setTime(DateUtil.beginOfDay(dto.getTime()));
        }
        dto.setWorkingStatus("0");
        var re = queryPage(dto, pageRequest);
       var sum= queryHelper.entityQuery(DailyWage.class).whereObject(dto).select(d -> Select.DRAFT.of(d.wage().sum())).firstOrNull();
        re.ExtendMapSet("wageSum",sum.getValue1());
        re.getRows().forEach(p -> p.ExtendMapSet("wage_new", p.calcRatioWageByBase(p.getRatioBaseFinal())));
        return re;
    }

     @ApiOperation("查询班组日工资")
     @PreAuthorize("@ps.any(@pay.dailyWage.list)")
     @GetMapping("listByDept")
     public ResultRows<DailyWage> listByDept(DailyWage dto, PageSort pageRequest) {
         if (dto.getDeptId() == null)
             dto.setDeptId(getDeptId());

         if (dto.getTime() == null)
             return ResultRows.bad("日期不能为空");
         if (dto.getTime() != null && dto.getTime2() == null) {
             dto.setTime2(DateUtil.endOfDay(dto.getTime()));
             dto.setTime(DateUtil.beginOfDay(dto.getTime()));
         }

         gainPageDomain(pageRequest);
         var reData = queryHelper.query().queryable(DailyWage.class)
                 .whereObject(dto != null, dto)
                 .where(p->p.in(DailyWage::getWorkingStatus,new String[]{"0","1"}))
                 .orderByAsc(p->p.column(DailyWage::getPostStatus))
                 .orderByAsc(p->p.column(DailyWage::getOrderNum))
                 .orderByDesc(p->p.column(DailyWage::getPostType))
                 .orderByDesc(p->p.column(DailyWage::getRatio))
                 .orderByAsc(d ->d.column(DailyWage::getId))
                 .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
         var re=toResultRows(reData);
         //
         //var re = queryPage(dto, pageRequest);
         var dept = queryHelper.entityQuery(Department.class).whereById(dto.getDeptId()).firstOrNull();
         if (dept!=null&&dept.getLineId() != null) {
             var outputGroup = queryHelper.entityQuery(OutputGroup.class)
                     .where(o -> o.sourceId().eq(dept.getLineId()))
                     .where(o -> o.time().rangeClosed(dto.getTime(), dto.getTime2()))
                     .where(o -> o.status().eq("1"))
                     .firstOrNull();
             re.getRows().forEach(p->{
                 if(p.getPostType()==1&&p.getFixedWage()==null) {
                     p.setFixedWage(p.getFixedPost());
                     p.setFixedPost(p.getFixedPost());
                 }
//                 else if(p.getPostType()==2&&p.getOutputNum()==null){
//                     p.setOutputNum(1);
//                 }
             });
             re.getRows().forEach(p -> p.ExtendMapSet("outputGroupNum", outputGroup == null ? null : outputGroup.getOutputNum()));
         }
         re.getRows().forEach(p -> p.ExtendMapSet("wage_new", p.calcRatioWageByBase(p.getRatioBaseFinal())));
         return re;
     }


    @ApiOperation("新增")
    @PreAuthorize("@ps.any(@pay.dailyWage.add)")
    @Log(title = "日工资", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody DailyWage entity){
       return super.add(entity);
    }

    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.dailyWage.remove)")
    @Log(title = "日工资", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        for (var id:ids)
        {
            var entity=queryHelper.queryable(DailyWage.class).whereById(id).firstOrNull();
            if(!Objects.equals(entity.getStatus(), "0"))
            {
                return Result.bad("只有草稿状态才能删除！"+id);
            }
            if(!Objects.equals(entity.getPostStatus(), "1"))
            {
                return Result.bad("只有副岗才可删除！"+id);
            }
        }
        return super.remove(Arrays.stream(ids).toArray());
    }

    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.dailyWage.edit)")
    @Log(title = "日工资", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody DailyWage entity){
        return super.edit(entity);
    }

     @ApiOperation("导出")
     @PreAuthorize("@ps.any(@pay.dailyWage.export)")
     @Log(title = "日工资", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
     public void export(DailyWage entity, PageDomain pageRequest,HttpServletResponse response)
     {
         entity.setTime2(DateUtil.endOfDay(entity.getTime()));
         super.export(entity,pageRequest,null,response);
     }

    @Resource
    WageSvc wageSvc;
     @ApiOperation("日工资单生成")
     @PreAuthorize("@ps.any(@pay.dailyWage.add)")
     @Log(title = "日工资", businessType = BusinessType.INSERT)
     @PostMapping("/createDailyBill")
    public Result createDailyBill(){
        wageSvc.createDailyBill(new Date());
        return Result.ok();
    }
     @ApiOperation(value = "手动创建日工资单",notes = "参数 {userId:用户id,time:日期,postId:岗位id,deptId:部门id}")
     @PreAuthorize("@ps.any(@pay.dailyWage.add)")
     @Log(title = "日工资", businessType = BusinessType.INSERT)
     @PostMapping("/createDailyWage")
     public Result createDailyWage(@RequestBody DailyWage dto) {
         return wageSvc.createDailyWage(dto);
     }
     @ApiOperation("日产量等信息提交")
     @PreAuthorize("@ps.any(@pay.dailyWage.edit)")
     @Log(title = "日工资", businessType = BusinessType.UPDATE)
     @PostMapping("/submitDailyBill")
     @Transactional
     public Result submitDailyBill(@RequestBody DailyWage[] dailyWages){

        return wageSvc.submitDailyBill(Arrays.asList(dailyWages));
     }

     @ApiOperation("领导日产量等信息修改")
     @PreAuthorize("@ps.any(@pay.dailyWage.edit)")
     @Log(title = "日工资", businessType = BusinessType.UPDATE)
     @PostMapping("/editDailyBill")
     @Transactional
     public Result editDailyBill(@RequestBody DailyWage[] dailyWages){
         return wageSvc.editLeaderDailyBill(Arrays.asList(dailyWages));
     }
     //日工资修改


 }
